package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import cn.tedu._03vehicle.mapper.UserMapper;
import cn.tedu._03vehicle.pojo.dto.UserLoginParam;
import cn.tedu._03vehicle.pojo.dto.UserRegParam;
import cn.tedu._03vehicle.pojo.entity.User;
import cn.tedu._03vehicle.pojo.vo.UserVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;


@Slf4j
@RestController
@RequestMapping("/v1/user/")
@Api(tags = "01.用户管理模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody UserRegParam userRegParam){
        log.debug("userRegParam + " + userRegParam);
        String username = userRegParam.getUsername();
        int i = userMapper.selectByUsername(username);
        if(i>0){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        log.debug("user="+user);
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @PostMapping("login")
    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam,@ApiIgnore HttpSession session) {
        log.debug("userLoginParam = " + userLoginParam);
        int i = userMapper.selectByUsername(userLoginParam.getUsername());
        if (i > 0) {
            UserVo userVO = userMapper.selectIdAndUsername(userLoginParam.getUsername(), userLoginParam.getPassword());
            if (userVO != null) {
                session.setAttribute("user", userVO);
                return JsonResult.ok(userVO);
            }
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        return new JsonResult(StatusCode.USERNAME_NOT_EXISTS);
    }
     @GetMapping("currentUser")
     @ApiOperation("获取当前用户功能")
     @ApiOperationSupport(order = 30)
     public JsonResult getcurrentUser(@ApiIgnore HttpSession session){
         UserVo userVO = (UserVo) session.getAttribute("user");
         return JsonResult.ok(userVO);

     }

     @GetMapping("logout")
     @ApiOperation("退出登录功能")
     @ApiOperationSupport(order = 40)
     public void logout(@ApiIgnore HttpSession session){
         session.removeAttribute("user");

     }




    }


